//
//  UIColor+public extension.swift
//  AJiTai
//
//  Created by BO ZHOU on 2020/5/17.
//  Copyright © 2020 BO ZHOU. All rights reserved.
//

import UIKit
 
public extension UIColor {
    
    
    static func fromHex(_ hexString: String) -> UIColor {
        return UIColor(hexString: hexString);
    }
     
    // Hex String -> UIColor
    convenience init(hexString: String) {
        
        if hexString.count == 7 {
            let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
            let scanner = Scanner(string: hexString)
             
            if hexString.hasPrefix("#") {
                scanner.scanLocation = 1
            }
             
            var color: UInt32 = 0
            scanner.scanHexInt32(&color)
             
            let mask = 0x000000FF
            let r = Int(color >> 16) & mask
            let g = Int(color >> 8) & mask
            let b = Int(color) & mask
             
            let red   = CGFloat(r) / 255.0
            let green = CGFloat(g) / 255.0
            let blue  = CGFloat(b) / 255.0
             
            self.init(red: red, green: green, blue: blue, alpha: 1)
        } else {
            
            // 长度为9位的情况, 前两位作为透明度
            let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
            let scanner = Scanner(string: hexString)
             
            if hexString.hasPrefix("#") {
                scanner.scanLocation = 1
            }
             
            var color: UInt32 = 0
            scanner.scanHexInt32(&color)
             
            let mask = 0x000000FF
            let a = Int(color >> 24) & mask
            let r = Int(color >> 16) & mask
            let g = Int(color >> 8) & mask
            let b = Int(color) & mask
             
            let red   = CGFloat(r) / 255.0
            let green = CGFloat(g) / 255.0
            let blue  = CGFloat(b) / 255.0
            let alpha = CGFloat(a) / 255.0
             
            self.init(red: red, green: green, blue: blue, alpha: alpha)
        }

    }
     
    // UIColor -> Hex String
    var hexString: String? {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
         
        let multiplier = CGFloat(255.999999)
         
        guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
            return nil
        }
         
        if alpha == 1.0 {
            return String(
                format: "#%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
        else {
            return String(
                format: "#%02lX%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier),
                Int(alpha * multiplier)
            )
        }
    }
}
